package com.servlet;

import com.bean.BookBean;
import com.dao.BooksDao;
import com.dao.impl.BooksDaoImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JdbcUtil;
import com.util.JsonUtil;
import com.util.ProxyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/BookServlet")

public class BookServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BooksDaoImpl booksDao = new BooksDaoImpl();
        BooksDao booksDao1 = (BooksDao) ProxyUtil.getDaoProxy(booksDao);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        JsonUtil jsonUtil =new JsonUtil();

        try {
            List<BookBean> bookBeans = booksDao1.queryData(null);
            jsonUtil.setMsg("成功");
            jsonUtil.setData(bookBeans);

        } catch (Exception e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("系统错误");

        }
        //利用API将任意的Java对象转换为Json
        GsonBuilder builder = new GsonBuilder();
        Gson gson =  builder.create();//创建Gson对象

        String jsonStr =  gson.toJson(jsonUtil);
        System.out.println("把BookBeanList转换为json格式字符串后的结果为:");
        System.out.println(jsonStr);

        out.print(jsonStr);//往客户端浏览器输出

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}
 
 
 

